/**
 * Created on 2007-03-25 18:48
 */
package game.media;

import java.applet.Applet;
import java.applet.AudioClip;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import manager.Manager;
import game.media.audio.Sound;

/**
 * @author David Wallin
 */
public class MediaManager extends Manager
{
	/**
	 * The one instance of this class
	 */
	public static final MediaManager		INSTANCE = new MediaManager();
	
	public static final String				DEFAULT_MEDIA_PATH = "http://david.pansarvagn.net/3tris/resources/";
	public static final String				SOUND_DROP = "audio/drop.wav";
	public static final String				SOUND_GAME_OVER = "audio/gameover.wav";
	public static final String				SOUND_LAND = "audio/land.wav";
	public static final String				SOUND_LEVELUP = "audio/levelup.wav";
	public static final String				SOUND_MOVE = "audio/move.wav";
	public static final String				SOUND_PAUSE = "audio/pause.wav";
	public static final String				SOUND_REMOVELINE = "audio/removeline.wav";
	public static final String				SOUND_REMOVELINE_SPECIAL = "audio/removeline_special.wav";
	public static final String				SOUND_ROTATE = "audio/rotate.wav";
	public static final String				SOUND_UNPAUSE = "audio/unpause.wav";
	
	private String							m_MediaPath;
	private HashMap<String, Sound>			m_Sounds;
	
	public Sound getAudioClip(String fileName)
	{
		Sound sound = null;
		
		if(m_Sounds.containsKey(fileName))
		{
			sound = m_Sounds.get(fileName);
		}
		else
		{
			URL snd = null;
			AudioClip clip = null;
			boolean loaded = true;
			
			try
			{
				snd = new URL(m_MediaPath + fileName);
				snd.openConnection().getInputStream().close();
				clip = Applet.newAudioClip(snd);
			}
			catch(MalformedURLException e) //media path is off
			{
				System.out.println("media path is off");
				loaded = false;
			}
			catch(IOException e) //media is missing
			{
				System.out.println("media is missing");
				loaded = false;
			}
			
			if(loaded)
			{
				sound = new Sound(clip);
				m_Sounds.put(fileName, sound);
			}
		}
		
		return sound;
	}
	
	public void setMediaPath(String mediaPath)
	{
		m_MediaPath = mediaPath;
	}
	
	protected void doInitialize()
	{
		
	}
	
	protected void doTearDown()
	{
		
	}
	
	protected void doUpdate(int deltaTime)
	{
		
	}
	
	private MediaManager()
	{
		m_Sounds = new HashMap<String, Sound>();
		m_MediaPath = DEFAULT_MEDIA_PATH;
	}
}
